import { defineStore } from 'pinia';

import { getToken, setToken, removeToken } from '@/utils/auth';
import { store } from '@/store';
import { LoginData } from '@/api/auth/types';
import { ref } from 'vue';
import { myInfoApi, loginApi, codeLoginApi } from '@/api/user';
import router from '@/router';

export const useUserStore = defineStore('user', () => {
  // state
  const token = ref<string>(getToken() || '');
  // const nickname = ref<string>('');
  // const avatar = ref<string>('');
  const name = ref<string>('');
  const photo = ref<string>('');
  const roles = ref<Array<string>>([]); // 用户角色编码集合 → 判断路由权限
  const perms = ref<Array<string>>([]); // 用户权限编码集合 → 判断按钮权限

  // actions

  // 登录
  async function login(loginData: any) {
    const data = loginData.code2 ? await codeLoginApi(loginData) : await loginApi(loginData)
    if(data.code === 200) {
      token.value = data.data
      setToken(data.data)
      router.push('/')
    }
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  async function getInfo() {
    const info = await myInfoApi()
    if(info.code === 200) {
      name.value = info.data.name
      photo.value = info.data.photo
      roles.value = info.data.roles
      perms.value = info.data.perms
      return {roles: roles.value, perms: perms.value}
    }
    return {roles: [], perms: []}
  }

  // 注销
  function logout() {
    resetToken()
    window.location.reload()
  }

  // 重置
  function resetToken() {
    removeToken();
    token.value = '';
    name.value = '';
    photo.value = '';
    roles.value = [];
    perms.value = [];
  }
  return {
    token,
    name,
    photo,
    roles,
    perms,
    login,
    getInfo,
    logout,
    resetToken
  };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
